import { ContentScriptContext } from '#imports'
import App from './App.vue'
import { createApp } from 'vue'
import './reset.css'
import { getValidAnchor } from '@/config/site-config'

export default defineContentScript({
    matches: ['<all_urls>'],
    cssInjectionMode: 'ui',

    async main(ctx) {
        importCss(browser.runtime.getURL('inject.css' as any), 'inject_css')

        await waitForDOMReady()

        const ui = await defineOverlay(ctx)

        // Mount initially
        ui.mount()

        // Re-mount when page changes
        ctx.addEventListener(window, 'wxt:locationchange', (event) => {
            ui.mount()
        })
    }
})

/**
 * 等待DOM完全加载
 */
function waitForDOMReady(): Promise<void> {
    return new Promise((resolve) => {
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', () => resolve())
        } else {
            resolve()
        }
    })
}

/**
 * 载入 css 文件
 * @param {*} src css 路径
 * @param {*} id link 标签 ID
 */
function importCss(src: string, id: string) {
    var css = document.createElement('link')
    css.rel = 'stylesheet'
    css.href = src
    css.id = id || 'C' + new Date().getTime()
    document.getElementsByTagName('head')[0].appendChild(css)
}

function defineOverlay(ctx: ContentScriptContext) {
    // 动态获取当前网站的anchor选择器
    const currentAnchor = getValidAnchor()

    console.log(`[Doctor Assistant] Using anchor selector: .other-container for ${window.location.href}`)

    return createShadowRootUi(ctx, {
        name: 'doctor-overlay',
        position: 'inline',
        anchor: currentAnchor,
        onMount(container) {
            const app = createApp(App)
            app.mount(container)
            return app
        },
        onRemove(app) {
            app?.unmount()
        }
    })
}
